package com.example.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.bean.*;
import com.example.demo.service.*;
import com.example.demo.utils.BaseResponse;
import com.example.demo.utils.FileUtil;
import com.example.demo.utils.SystemStatusEnum;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import okhttp3.*;
import okhttp3.RequestBody;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author
 * @date 2020/6/24 23:49
 * @desc 描述
 */
@CrossOrigin
@RestController
@RequestMapping(value = "user")
@Api(tags = "用户接口")
public class AffairController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(AffairController.class);

    @Value("${web.upload-path}")
    private String path;

    @Value("${server.servlet.context-path}")
    private String context_path;

    @Value("${web.image-path}")
    private String imagePath;

    @Autowired
    private UserService affairService;


    @Autowired
    private TimetableService timetableService;

    @Autowired
    private FileService fileService;

    @Autowired
    GroupService groupService;

    @Autowired
    GroupMessageService groupMessageService;

    @Autowired
    ClassesService classesService;


    //    @ApiOperation 使用于在方法上，表示一个http请求的操作
    //    @PostMapping，处理post请求
    //    @RequestParam将请求参数绑定到控制器的方法参数上（是springmvc中接收普通参数的注解）
    @CrossOrigin
    @ApiOperation(value = "注册", nickname = "xxxx", notes = "注册接口")
    @PostMapping(value = "/register")
    private BaseResponse register(@RequestParam(name = "account") String account,
                                  @RequestParam(name = "nickname") String nickname,
                                  @RequestParam(name = "spIdentity") String spIdentity,
                                  @RequestParam(name = "password") String password,
                                  @RequestParam(name = "classes",required = false) String classes) {


        UserBean userBean = getEntityFromRequest(UserBean.class);
        try {
            UserBean end = affairService.addUser(userBean);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse(SystemStatusEnum.FAIL, "用户已存在");
        }
        return new BaseResponse(SystemStatusEnum.SUCCESS, "注册成功");
    }

    @CrossOrigin
    @ApiOperation(value = "登录", nickname = "xxxx", notes = "登录接口")
    @PostMapping(value = "/login")
    private BaseResponse login(@RequestParam(name = "account") String account,
                               @RequestParam(name = "password") String password,
                               @RequestParam(name = "spIdentity") String spIdentity) {
        UserBean userBean = affairService.login(account, password,spIdentity);

        if (userBean != null) {
            return new BaseResponse(SystemStatusEnum.SUCCESS, "登录成功", userBean);
        } else {
            return new BaseResponse(SystemStatusEnum.FAIL, "---用户名或密码或身份错误");
        }
    }

    @CrossOrigin
    @ApiOperation(value = "查看个人信息", nickname = "xxxx", notes = "查看个人信息接口")
    @PostMapping(value = "/detail")
    private BaseResponse detail(@RequestParam(name = "account") @ApiParam("账号") String account) {
        UserBean detail = affairService.findByAccount(account);
        if (detail != null) {
            return new BaseResponse(SystemStatusEnum.SUCCESS, detail);
        } else {
            return new BaseResponse(SystemStatusEnum.FAIL, "个人信息不存在");
        }
    }

    @CrossOrigin
    @ApiOperation(value = "查看个人信息id", nickname = "xxxx", notes = "查看个人信息id接口")
    @PostMapping(value = "/detailById")
    private BaseResponse detailById(@RequestParam(name = "userid") @ApiParam("用户id") String userid) {
        UserBean detail = affairService.findByObjId(userid);
        if (detail != null) {
            return new BaseResponse(SystemStatusEnum.SUCCESS, detail);
        } else {
            return new BaseResponse(SystemStatusEnum.FAIL, "人员信息不存在");
        }
    }


    @CrossOrigin
    @ApiOperation(value = "修改密码", nickname = "xxxx", notes = "修改密码")
    @PostMapping(value = "/updatePwd")
    private BaseResponse updatePwd(@RequestParam(name = "userid") String userid,
                                   @RequestParam(name = "password") String password) {

        UserBean userBean = affairService.findByObjId(userid);
        userBean.setPassword(password);
        affairService.addUser(userBean);
        return new BaseResponse(SystemStatusEnum.SUCCESS, "密码修改成功");
    }


    @CrossOrigin
    @ApiOperation(value = "用户人员删除", nickname = "xxxx", notes = "删除用户人员信息接口")
    @PostMapping(value = "/delUser")
    private BaseResponse delUser(@RequestParam(name = "userId") @ApiParam("用户人员id") String userId) {
        BaseResponse response = new BaseResponse();
        response.setCode(SystemStatusEnum.SUCCESS.getCode());
        response.setMessage("删除成功");

        affairService.deleteByUserObjId(userId);
        return response;
    }

    @ApiOperation(value = "查询老师列表", nickname = "xxxx", notes = "查询老师列表")
    @PostMapping(value = "/teachersList")
    private BaseResponse teachersList() {
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", affairService.findTeachers());
    }


    @ApiOperation(value = "添加课表", nickname = "xxxx", notes = "添加课表接口")
    @PostMapping(value = "/addTimetable")
    private BaseResponse addTimetable(@RequestParam (name = "classname") @ApiParam("班级名称") String className,
                                      @RequestParam (name = "courseName") @ApiParam("课表名称") String courseName,
                                      @RequestParam (name = "week") @ApiParam("上课星期") String week,
                                      @RequestParam (name = "start_node") @ApiParam("课程开始节数(数字1——12),若课程只有一节,开始与结束相同") int start_node,
                                      @RequestParam (name = "end_node") @ApiParam("课程结束节数(数字1——12),若课程只有一节,开始与结束相同") int end_node){

        TimetableBean timetableBean = getEntityFromRequest(TimetableBean.class);
        timetableService.addTimetable(timetableBean);
        return new BaseResponse(SystemStatusEnum.SUCCESS, "课表添加成功");
    }

    @ApiOperation(value = "删除课表", nickname = "xxxx", notes = "删除课表接口")
    @PostMapping(value = "/delTimetable")
    private BaseResponse delTimetable(@RequestParam (name = "objId") @ApiParam("课表id") String objId){
        timetableService.delTimetable(objId);
        return new BaseResponse(SystemStatusEnum.SUCCESS, "课表删除成功");
    }

    @ApiOperation(value = "查询课表列表", nickname = "xxxx", notes = "查询所有课表接口")
    @PostMapping(value = "/timetableList")
    private BaseResponse timetableList(@RequestParam(defaultValue = "1", name = "pageNum") @ApiParam("页码") String pageNum,
                                       @RequestParam(defaultValue = "55", name = "pageSize") @ApiParam("一页个数") String pageSize,
                                       @RequestParam(required=false, name = "userId") @ApiParam("用户id") String userId,
                                       @RequestParam(required=false, name = "class_name") @ApiParam("班级") String class_name){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", timetableService.timetableList(Integer.valueOf(pageNum)-1, Integer.valueOf(pageSize), userId,class_name));
    }

    @ApiOperation(value = "添加用户课表关系", nickname = "xxxx", notes = "添加用户课表关系接口")
    @PostMapping(value = "/addUserTimeableZJ")
    private BaseResponse addUserTimeableZJ(@RequestParam (name = "userId") @ApiParam("用户id") String userId,
                                           @RequestParam (name = "timetableId") @ApiParam("课表id") String timetableId,
                                           @RequestParam (name = "classname") @ApiParam("班级名称") String classname){
        List<Map<String, Object>> userBeans = timetableService.findUserTimeableZJ(timetableId);
        if (userBeans.size()>0){
            return new BaseResponse(SystemStatusEnum.FAIL, "---该课程已有授课老师");
        }else {
            UserTimetableZJBean bean = getEntityFromRequest(UserTimetableZJBean.class);
            timetableService.addUserTimeableZJ(bean);
            return new BaseResponse(SystemStatusEnum.SUCCESS, "添加成功");
        }

    }


    @ApiOperation(value = "查询当前授课老师", nickname = "xxxx", notes = "查询当前授课老师")
    @PostMapping(value = "/selectTeacher")
    private BaseResponse selectTeacher(@RequestParam (name = "timetableId") @ApiParam("课表id") String timetableId){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", timetableService.findUserTimeableZJ(timetableId));
    }

    @CrossOrigin
    @ApiOperation(value = "授课老师删除", nickname = "xxxx", notes = "授课老师删除")
    @PostMapping(value = "/delTeacher")
    private BaseResponse delTeacher(@RequestParam (name = "timetableId") @ApiParam("课表id") String timetableId) {
        BaseResponse response = new BaseResponse();
        response.setCode(SystemStatusEnum.SUCCESS.getCode());
        response.setMessage("删除成功");

        timetableService.deleteTeacher(timetableId);
        return response;
    }

    @ApiOperation(value = "查询老师所授科目", nickname = "xxxx", notes = "查询当前授课老师")
    @PostMapping(value = "/selectTeachertask")
    private BaseResponse selectTeachertask(@RequestParam (name = "userid") @ApiParam("老师id") String userid){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", timetableService.findTimeableZJ(userid));
    }

    @ApiOperation(value = "查询作业", nickname = "xxxx", notes = "查询作业")
    @PostMapping(value = "/selectTask")
    private BaseResponse selectTask(@RequestParam (name = "timetable_id") @ApiParam("课程id") String timetable_id){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", fileService.findTask(timetable_id));
    }

    @ApiOperation(value = "查询小组", nickname = "xxxx", notes = "查询作业")
    @PostMapping(value = "/selectGroup")
    private BaseResponse selectGroup(){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", groupService.findGroupBean());
    }

    @ApiOperation(value = "添加小组", nickname = "xxxx", notes = "添加小组")
    @PostMapping(value = "/addGroup")
    private BaseResponse addGroup(@RequestParam (name = "userId") @ApiParam("组员id") String userId,
                                      @RequestParam (name = "groupName") @ApiParam("小组名称") String groupName,
                                      @RequestParam (name = "master",required = false) @ApiParam("群主(1为群主)") String master){

        GroupBean groupBean = getEntityFromRequest(GroupBean.class);
        groupService.addGroup(groupBean);
        return new BaseResponse(SystemStatusEnum.SUCCESS, "添加小组成功");
    }

    @ApiOperation(value = "查看是否有群组", nickname = "xxxx", notes = "查看是否有群组")
    @PostMapping(value = "/selectisGroup")
    private BaseResponse selectisGroup(
            @RequestParam(name = "cuserid") @ApiParam("用户id") String cuserid){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功",  groupService.findisGroupBean(cuserid));
    }

    @CrossOrigin
    @ApiOperation(value = "小组删除", nickname = "xxxx", notes = "小组删除")
    @PostMapping(value = "/delGroup")
    private BaseResponse delGroup(@RequestParam (name = "timetableId") @ApiParam("课表id") String timetableId) {
        BaseResponse response = new BaseResponse();
        response.setCode(SystemStatusEnum.SUCCESS.getCode());
        response.setMessage("删除成功");

        groupService.deleteGroup(timetableId);
        return response;
    }

    @ApiOperation(value = "小组留言", nickname = "xxxx", notes = "小组留言")
    @PostMapping(value = "/groupMessage")
    private BaseResponse groupMessage(@RequestParam(name = "groupName") @ApiParam("群组名称") String groupName,
                                          @RequestParam(name = "gmessage") @ApiParam("留言内容") String gmessage,
                                          @RequestParam(name = "gmessageuserid") @ApiParam("留言人id") String gmessageuserid,
                                      @RequestParam(name = "gmessageusername") @ApiParam("留言人姓名") String gmessageusername) {
        GroupMessageBean groupMessageBean = getEntityFromRequest(GroupMessageBean.class);

        GroupMessageBean savebean = groupMessageService.addGroupMessageBean(groupMessageBean);
        if (savebean != null) {
            return new BaseResponse(SystemStatusEnum.SUCCESS, "小组留言成功");
        } else {
            return new BaseResponse(SystemStatusEnum.FAIL, "小组留言失败");
        }

    }

    @ApiOperation(value = "查询小组留言", nickname = "xxxx", notes = "查询小组留言")
    @PostMapping(value = "/selectGroupMessage")
    private BaseResponse selectGroupMessage(@RequestParam(name = "groupName") @ApiParam("群组名称") String groupName){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", groupMessageService.findGroupMessageBean(groupName));
    }

    @ApiOperation(value = "查询学生作业", nickname = "xxxx", notes = "查询学生作业")
    @PostMapping(value = "/selectStudentTask")
    private BaseResponse selectStudentTask(@RequestParam(name = "timetable_id") @ApiParam("课程id") String timetable_id){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", fileService.findStudentTask(timetable_id));
    }

    @CrossOrigin
    @ApiOperation(value = "老师作业留言", nickname = "xxxx", notes = "老师作业留言")
    @PostMapping(value = "/updateTaskMsg")
    private BaseResponse updateTaskMsg(@RequestParam(name = "obj_id") String obj_id,
                                   @RequestParam(name = "teachermsg") String teachermsg) {

        StudentFileBean studentFileBean = fileService.findByObjId(obj_id);
        studentFileBean.setTeachermsg(teachermsg);
        fileService.addStuFile(studentFileBean);
        return new BaseResponse(SystemStatusEnum.SUCCESS, "老师作业留言成功");
    }

    @ApiOperation(value = "查询学生作业提交情况", nickname = "xxxx", notes = "查询学生作业提交情况")
    @PostMapping(value = "/selectTaskStatistics")
    private BaseResponse selectTaskStatistics(@RequestParam(name = "timetable_id") @ApiParam("课程id") String timetable_id){
        int submitted = fileService.findTimetableCount(timetable_id);
        int alls = affairService.findStudentCount();
        BaseResponse response = new BaseResponse();
        response.setCode(SystemStatusEnum.SUCCESS.getCode());
        response.setMessage("请求成功");
        Map<String, Object> map = new HashMap<>();
        map.put("submitted", submitted);
        map.put("allstudent", alls);
        response.setData(map);
        return response;
    }

    @ApiOperation(value = "创建班级", nickname = "xxxx", notes = "创建班级")
    @PostMapping(value = "/createClass")
    private BaseResponse createClass(@RequestParam (name = "className") @ApiParam("班级名称") String className) {

        ClassesBean classesBean = getEntityFromRequest(ClassesBean.class);
        classesService.addClass(classesBean);
        return new BaseResponse(SystemStatusEnum.SUCCESS, "添加班级成功");
    }

    @ApiOperation(value = "查询班级", nickname = "xxxx", notes = "查询班级")
    @PostMapping(value = "/selectClass")
    private BaseResponse selectClass(){
        return new BaseResponse(SystemStatusEnum.SUCCESS, "获取成功", classesService.findClassBean());
    }
}
